package club.itstudio.itouc.core.annotation

import club.itstudio.itouc.config.ElectiveCoursecConfig
import club.itstudio.itouc.service.JwOps
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import java.util.concurrent.ConcurrentSkipListSet

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class ReqStatistic

// the size of map is the num of real time req
val ReqMap = ConcurrentSkipListSet<Long>()

@Aspect
@Component
class ReqStatisticHandler(val ecConfig: ElectiveCoursecConfig,
                          val jwOps: JwOps) {
    @Around("@annotation(club.itstudio.itouc.core.annotation.ReqStatistic)")
    fun access(joinPoint: ProceedingJoinPoint): Any {
        var res = Any()
        val reqTime = System.currentTimeMillis()
        // 添加时间戳
        if (ReqMap.add(reqTime)){
            try {
                res = joinPoint.proceed()
            }finally {
                // 移除时间戳
                ReqMap.remove(reqTime)
            }
        }
        return res
    }
}


@Service
class DeleteReqMap{
    // 每两分钟检查一次
    @Scheduled(cron = "0 0/2 * * * ?")
    fun delete() {
        val now = System.currentTimeMillis()
        for (l in ReqMap) {
            if (now - l > 30 * 1000){
                ReqMap.remove(l)
            }
        }
    }
}
